package com.xyg.controller;


import com.xyg.pojo.Product;
import com.xyg.pojo.Result;
import com.xyg.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping( "/api/products" )
public class ProductController {

    @Autowired
    private ProductService productService;

    //* 获取所有商品: /api/products
    @GetMapping
    public Result< List< Product > > getAllProducts () {
        List< Product > productList = productService.findAll();
        if ( productList.isEmpty() ) {
            return Result.failure( 404, "没有找到商品" );
        }
        return Result.success( "获取商品列表成功", productList );
    }

    //* 根据ID获取单个商品: /api/products/{id}
    @GetMapping( "/{id}" )
    public Result< Product > getProductById ( @PathVariable String id ) {
        if ( id == null || id.isEmpty() ) {
            return Result.failure( 400, "商品ID不能为空" );
        }
        Optional< Product > product = productService.findById( id );
        return product.map( p -> Result.success( "获取指定商品信息成功", p ) )
                .orElseGet( () -> Result.failure( 404, "商品未找到" ) );
    }


}